﻿namespace ElisVK.Data.AudioSources
{
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using Utils;

    public class VKSubscriptionsAudioSource : AudioSource
    {
        public VKSubscriptionsAudioSource()
            : base("VK Subscriptions", true)
        {
        }
        
        protected override void LoadChildren()
        {
            var buff = VKHelper.DownloadData(
                "https://api.vkontakte.ru/method/subscriptions.get.xml?count=1000&access_token=" +
                App.SessionInfo.AccessToken);

            var xmlDocument = new XmlDocument();
            var uids = new StringBuilder();

            xmlDocument.LoadXml(Encoding.UTF8.GetString(buff));

            if (xmlDocument.ChildNodes.Cast<XmlNode>().Any(node => node.Name == "error"))
            {
                return;
            }

            var dataSet = new DataSet();

            dataSet.ReadXml(new StringReader(xmlDocument.InnerXml), XmlReadMode.InferSchema);

            if (dataSet.Tables["uid"] != null && dataSet.Tables["uid"].Rows.Count > 0)
            {
                foreach (DataRow dataRow in dataSet.Tables["uid"].Rows)
                {
                    if (dataRow.ItemArray.Length > 0)
                        uids.Append(dataRow.ItemArray[0].ToString() + ',');
                }
            }

            if (uids.Length > 0 && uids.ToString().EndsWith(","))
                uids.Remove(uids.Length - 1, 1);

            buff = VKHelper.DownloadData(
                string.Format("https://api.vkontakte.ru/method/users.get.xml?uids={0}&fields=uid,first_name,last_name&access_token={1}", uids, App.SessionInfo.AccessToken));
            
            var friendsList = UserInfo.ParseUserInfosFromXML(Encoding.UTF8.GetString(buff));

            friendsList.Sort();

            foreach (var friend in friendsList)
            {
                Children.Add(new VKFriendAudioSource(friend));
            }
        }
    }
}
